import React, { Component, Fragment } from 'react';
import { Card, DatePicker, Table, notification, Button, Form, Row, Col, Avatar, InputNumber, Input } from 'antd';
import styles from './deliveryPlan.less';
import dayjs from 'dayjs';
import moment from 'moment';
import { useEffect, useRef, useState } from 'react';
import request from '@/utils/request';
import { listSort } from '@/utils/utils';
import PublicUtils from "@/utils/publicUtils";
import {
  FormOutlined,
  RightCircleFilled,
  UserOutlined
} from '@ant-design/icons';
const { RangePicker, MonthPicker } = DatePicker;

import { InfiniteScroll, SpinLoading, Popup } from 'antd-mobile';
import { ConfigProvider } from 'antd';
import zh_CN from 'antd/es/locale/zh_CN';
import locale from 'antd/locale/zh_CN';
import 'dayjs/locale/zh-cn';
dayjs.locale('zh-cn');

export default class deliveryPlan extends Component {
  constructor(props) {
    super(props);
    let userInfo = JSON.parse(localStorage.getItem('userInfo'));
    this.state = {
      loading: false,
      date: !this.props.location?.query.date ? moment().format('YYYY-MM') : moment(this.props.location?.query.date).format('YYYY-MM'),
      total: 0,
      pageNum: 1,
      pageSize: 20,
      formValues: {
        sort: 'desc',
        sortType: 'completion',
      }, //搜索关键字
      deliveryData: [],
      targetData: {},
      userInfo: userInfo,
      remark: '两鬓皤，中年过，图甚区区苦张罗。人间宠辱都参破。种春风二顷田，远红尘千丈波，倒大来闲快活。带月行，披星走，孤馆寒食故乡秋。妻儿胖了咱消瘦。枕上忧，马上愁，死后休。',
      hasMore: true,
      addVisible: false,
      detailVisible: false,
      warnVisible: false,
      month: moment(moment(this.props.location?.query.date).month() + 1, 'MM').format('MM'),
      detailData: {},
      tips: "请准确填写，这将影响你的绩效和奖金。",   // 提示信息
      message: '',
      addTargetDate: PublicUtils.getDictionary('SUBMIT_NEXT_TIME'),
      startTime: "",
      endTime: "",
    };
    this.formRef = React.createRef();
  }

  componentDidMount() {
    this.setState({
      startTime: PublicUtils.getDictionaryValue("START_TIME", this.state.addTargetDate),
      endTime: PublicUtils.getDictionaryValue("END_TIME", this.state.addTargetDate),
      message: '本月目标提交日期为上月' + PublicUtils.getDictionaryValue("START_TIME", this.state.addTargetDate) + '号至本月' + PublicUtils.getDictionaryValue("END_TIME", this.state.addTargetDate) + '号，当前时间不允许提交。'
    }, () => {
      if (PublicUtils.checkAuth('2020603_PERMS')) {
        this.getDeliveryTarget()
      }
      this.getDeliveryList()
    })

  }

  //设置为null的值为0
  setNullToZero = (obj) => {
    if (obj === null) {
      return 0;
    } else if (typeof obj === 'object' && obj !== null) {
      for (let key in obj) {
        obj[key] = this.setNullToZero(obj[key]);
      }
    }
    return obj;
  }

  //获取交付目标
  getDeliveryTarget = () => {
    request.get('/dashboard/getDeliveryTarget').then(res => {
      if (res && res.error_code === 200) {
        if (res.data && Object.keys(res.data).length > 0) {
          let processedData = this.setNullToZero(res.data);
          this.setState({
            targetData: processedData
          })
        } else {
          notification.warn({
            message: '数据为空'
          })
        }

      } else {
        notification.error({
          message: res ? res.error_msg : '请求错误'
        })
      }
    })
  }

  //获取交付计划列表
  getDeliveryList = () => {
    const { formValues, pageNum, deliveryData, pageSize, date } = this.state
    request.post('/deliveryPlan/getDataList', {
      data: {
        planYearMonth: moment(date).format('YYYY-MM'),
        pageNum,
        pageSize,
        ...formValues,
      }
    }).then(res => {
      if (res && res.error_code === 200) {
        //页数相同，直接替换
        if (res.data.current == 1) {
          this.setState({
            deliveryData: res.data ? res.data.records : [],
            total: res.data ? res.data.total : 0,
            loading: false,
            pageNum: pageNum,
            hasMore: true,
          })
        } else {
          const newData = res.data ? res.data.records : [];
          if (res.data.current > res.data.pages) {
            this.setState({ hasMore: false, loading: false });
            return;
          }

          this.setState({
            deliveryData: [
              ...deliveryData, // 将新获取的数据添加到已有的数据列表后面
              ...newData
            ],
            total: res.data ? res.data.total : 0,
            loading: false,
            pageNum: pageNum
          })
        }


      } else {
        notification.error({
          message: res ? res.error_msg : '请求错误'
        })
      }
    })
  }

  //交付数据详情
  detail = (record) => {
    this.setState(
      {
        staffId: record.staffId,
        detailVisible: true
      },
      () => {
        this.getDtailById();
      }
    );
  }


  //获取交付数据详情
  getDtailById = () => {
    const { staffId, detailData, date } = this.state;
    request
      .post('/deliveryPlan/getDetailById', {
        data: {
          staffId: staffId,
          planYearMonth: moment(date).format('YYYY-MM'),
        }
      })
      .then(res => {
        if (res && res.error_code === 200) {
          const detailData = res.data ? res.data : [];
          this.setState({ detailData: detailData });
        } else {
          notification.error({
            message: res ? res.error_msg : '请求错误'
          });
        }
      });
  };


  // 判断当前日期是否在给定的开始时间和结束时间之间，考虑各种情况
  isCurrentDateBetween = (startDate, endDate) => {
    const currentDate = moment();
    const currentMonth = moment().month();
    const prevMonth = moment().subtract(1, 'month').month();
    const nextMonth = moment().add(1, 'month').month();
    // const nextMonth = moment(endDate).add(1, 'month');

    // 将上月15号和本月1号转换为对应的日期对象，考虑跨月情况
    const startDatePrevToCurrent = moment().subtract(1, 'month').date(startDate).month(prevMonth);
    const endDatePrevToCurrent = moment().date(endDate).month(currentMonth);

    // 将本月15号和下月1号转换为对应的日期对象，考虑跨月情况
    const startDateCurrentToNext = moment().date(startDate).month(currentMonth);
    const endDateCurrentToNext = moment().add(1, 'month').date(endDate).month(nextMonth);

    // 判断当前日期是否在上月15号至本月1号之间
    const isBetweenPrevToCurrent = () => {
      if (startDatePrevToCurrent.isBefore(endDatePrevToCurrent)) {
        return currentDate.isBetween(startDatePrevToCurrent, endDatePrevToCurrent, null, '[]');
      } else {
        return currentDate.isBetween(startDatePrevToCurrent, moment().endOf('prevMonth'), null, '[]') ||
          currentDate.isBetween(moment().startOf('month'), endDatePrevToCurrent, null, '[]');
      }
    };

    // 判断当前日期是否在本月15号至下月1号之间
    const isBetweenCurrentToNext = () => {
      if (startDateCurrentToNext.isBefore(endDateCurrentToNext)) {
        return currentDate.isBetween(startDateCurrentToNext, endDateCurrentToNext, null, '[]');
      } else {
        return currentDate.isBetween(startDateCurrentToNext, moment().endOf('month'), null, '[]') ||
          currentDate.isBetween(moment().startOf('nextMonth'), endDateCurrentToNext, null, '[]');
      }
    };
    return isBetweenPrevToCurrent() || isBetweenCurrentToNext();
  };


  //提交下月目标
  addNextTarget = () => {
    const { startTime, endTime, detailData, message } = this.state;
    if (this.isCurrentDateBetween(startTime, endTime)) {
      this.setState({
        staffId: this.state.userInfo.staffId,
      }, () => {
        this.getDtailById()
        this.setState({ addVisible: true })
      })
    } else {
      this.setState({
        warnVisible: true,
      })
    }
  }


  //添加目标确定按钮
  addTarget = () => {
    const { detailData, date } = this.state
    this.formRef.current.validateFields()
      .then(values => {
        request.post('/deliveryPlan/submitNextMonthGoal', {
          data: {
            planYearMonth: moment(date).format('YYYY-MM'),
            staffId: detailData.staffId,
            deliveryPlanId: detailData.deliveryPlanId,
            target: values.target,
            description: values.description,
          }
        }).then(res => {
          if (res && res.error_code === 200) {
            notification.success({ message: '提交成功' })
            this.getDeliveryList()
            this.onClose()
            // this.setState({ addVisible: false })
          } else {
            notification.error({ message: res ? res.error_msg : '请求错误' })
          }
        })
      })
      .catch(info => {
        return false
      });
  }

  //关闭详情、警告弹出层
  onClose = () => {
    this.setState({
      detailVisible: false,
      warnVisible: false
    })
  }

  //关闭提交目标弹出层
  onCloseAdd = () => {
    this.setState({
      addVisible: false
    }, () => {
      this.formRef.current.resetFields();
    })
  }

  /**
* 表格总变化回调
*/
  onApprovalTableChange = (pagination, filters, sorter, extra) => {
    this.handleSettingsSorter(sorter);
  };
  /**
  * 表格Sorter变化回调
  */
  handleSettingsSorter = ({ order, field }) => {
    let question = {};
    if (!field) {
      this.setState({
        formValues: question
      }
      )
      return
    }
    const { formValues } = this.state;

    if (!order) {
      question = {
        ...formValues,
        sort: field === 'completion' ? 'asc' : 'desc',
        sortType: 'completion',
      }
    } else {
      question = {
        ...formValues,
        sort: order === 'descend' ? 'desc' : 'asc',
        sortType: field == 'completion' ? 'completion' : field
      }
    }
    this.setState({
      pageNum: 1,
      formValues: question
    }, () => {
      this.getDeliveryList();
    })


  };



  //日期选择变化
  onMonthPickerChange = (date, dateString) => {
    this.setState({
      date: dateString,
      loading: true,
      pageNum: 1,
      // pageSize: 20,
    }, () => {
      this.getDeliveryList()
    })
  }

  loadMore = () => {
    const { hasMore, loading, pageNum } = this.state;
    if (!loading && hasMore) {
      this.setState({ loading: true, pageNum: pageNum + 1 }, () => {
        this.getDeliveryList()
      })

    }
  }

  //数字输入-+操作
  onAdd = () => {
    let target = this.formRef.current.getFieldValue('target');
    if (target) {
      target = target + 1;
    } else {
      target = 0;
      target = target + 1;
    }
    this.formRef.current.setFieldsValue({
      target: target
    })
  }
  onReduce = () => {
    let target = this.formRef.current.getFieldValue('target');
    console.log(target)
    if (target) {
      target = target - 1;
    } else {
      target = 0;
      target = target - 1;
    }
    this.formRef.current.setFieldsValue({
      target: target
    })
  }

  render() {

    const {
      loading,
      deliveryData,
      date,
      total,
      pageSize,
      pageNum,
      month,
      userInfo,
      remark,
      targetData,
      hasMore,
      addVisible,
      detailData,
      tips,
      detailVisible,
      startTime,
      endTime,
      message,
      warnVisible
    } = this.state;


    // 交付计划列表
    const deliveryColumns = [
      {
        title: '姓名',
        dataIndex: 'staffName',
        width: '22%',
        render: (text, record, index) => <span>{!text ? record.staffName : text}</span>,
      },
      {
        title: '目标',
        dataIndex: 'target',
        width: '15%',
      },
      {
        title: '完成',
        dataIndex: 'completion',
        sorter: true,
        width: '15%',
        sortOrder: listSort('completion', this.state.formValues),
        // ellipsis: true,
        render: (text, record, index) => <a className={styles.marginR8} >{text}</a>
      },
      {
        title: '目标更新日期',
        dataIndex: 'targetUpdateDate',
        width: '25%',
        render: (text, record, index) => <span>{!text ? '-' : moment(text).format('YYYY-MM-DD')}</span>
      },
      {
        title: '',
        dataIndex: 'menuId',
        align: 'center',
        width: '23%',
        render: (text, record, index) => <div>
          {PublicUtils.checkAuth('2020588_PERMS') && <a className={styles.marginR8} onClick={() => this.detail(record)}><RightCircleFilled />详情</a>}
        </div>
      }
    ]

    const monthFormat = 'YYYY/MM';

    const formItemLayout = {
      labelCol: { span: 2 },
      wrapperCol: { span: 14 }
    }

    const locale = {
      emptyText: () => null, // 自定义为空时不显示任何东西
    };

    return (
      <ConfigProvider locale={zh_CN}>
        <div className={styles.contions}>
          {PublicUtils.checkAuth('2020603_PERMS') && <div className={styles.target}>
            {PublicUtils.checkAuth('2020604_PERMS') && <div className={this.isCurrentDateBetween(startTime, endTime)
              ? `${styles.targetButton}` // 否则设置为蓝色按钮样式
              : `${styles.targetButton} ${styles.grayButton}` // 满足条件设置为灰色按钮样式

            } onClick={this.addNextTarget}>
              <FormOutlined style={{ color: 'ffffff', fontSize: '16px' }} />  提交下月目标
            </div>}
            <div className={styles.targetContent}>
              <div className={styles.child + " " + styles.topLeft} >本月目标  <span style={{ fontSize: '34px', marginLeft: '20px' }}> {targetData?.target}</span></div>
              <div className={styles.child + " " + styles.bottomLeft}>本月完成<span style={{ fontSize: '34px', marginLeft: '20px' }}>{targetData?.completion}</span></div>
              <div className={styles.child + " " + styles.bottomRight}>下月目标<span style={{ fontSize: '34px', marginLeft: '20px' }}>{targetData?.nextTarget}</span></div>
            </div>
          </div>}
          <span  className={PublicUtils.checkAuth('2020603_PERMS') ? `${styles.remarkTop1}` : `${styles.remarkTop2}`} style={{ marginBottom: '10px' }}>
            <div className={styles.remark}>
              <div>说明:</div>
              <div>{remark}</div>
            </div>
            <div className={styles.date}>
              <ConfigProvider locale={locale}>
                <DatePicker style={{ width: '80%', height: '50px' }} onChange={this.onMonthPickerChange} picker="month" defaultValue={dayjs(date, monthFormat)} />
              </ConfigProvider>
            </div>
            <div className={styles.table}>
              <ConfigProvider
                theme={{
                  components: {
                    Table: {
                      cellPaddingInline: 4
                    },
                  },
                }}
              >
                <Table
                  className={styles.shadowTable}
                  rowKey="menuId"
                  bordered
                  align="center"
                  loading={loading}
                  dataSource={deliveryData}
                  columns={deliveryColumns}
                  pagination={false}
                  locale={locale}
                  onChange={this.onApprovalTableChange}
                  getPopupContainer={() => document.body}
                />
                <InfiniteScroll loadMore={this.loadMore} hasMore={hasMore} />
              </ConfigProvider>
            </div>
          </span>


          {/* 提交下月目标 */}
          <Popup
            visible={addVisible}
            onMaskClick={this.onCloseAdd}
            bodyStyle={{
              borderTopLeftRadius: '10px',
              borderTopRightRadius: '10px',
              minHeight: '65vh',
            }}
          >
            <div style={{ fontSize: '16px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '10px', borderBottom: '1px solid #ccc' }}>
              <Button
                type="link"
                onClick={this.onCloseAdd}
                style={{
                  fontSize: '16px',
                }}
              >
                取消
              </Button>
              <span>{'提交' + month + '月交付目标'}</span>
              <Button
                type="link"
                onClick={this.addTarget}
                style={{
                  fontSize: '16px',
                }}
                key="submit"
                htmlType="submit"
              >
                确定
              </Button>
            </div>
            <div style={{ padding: '10px' }}>
              <Form onFinish={this.addTarget} ref={this.formRef}>
                <Row
                  type="flex"
                  justify="space-between"
                  align="middle"
                  gutter={0}
                  style={{ padding: '14px 10px 0px 10px', color: '#fff' }}
                >
                  <Col span={7}>
                    <div style={{ width: "80px", height: '80px' }}>
                      {detailData.sysUserHead ? (
                        <Avatar src={detailData.sysUserHead} size={80} />
                      ) : (
                        <Avatar icon={<UserOutlined />} size={80} />
                      )}
                    </div>
                  </Col>
                  <Col span={17} >
                    <div
                      style={{ fontSize: "14px", color: "#333333" }}
                      title={detailData.staffName || detailData.staffName}
                    >
                      {detailData.staffName || detailData.staffName}
                    </div>
                    <div
                      style={{ marginTop: 5, fontSize: "12px", color: '#C9C9C9' }}
                      title={detailData.deptName + '-' + detailData.staffJobName}
                    >
                      部门：{detailData.deptName}
                    </div>
                    <div
                      style={{ marginTop: 5, fontSize: "12px", color: '#C9C9C9' }}
                      title={detailData.deptName + '-' + detailData.staffJobName}
                    >
                      职务：{detailData.staffJobName}
                    </div>
                  </Col>
                </Row>
                <Row
                  type="flex"
                  justify="space-between"
                  align="middle"
                  gutter={0}
                  style={{ width: 'calc(100% - 20px)', padding: '0px 10px', color: '#fff' }}>
                  <Col span={7}>
                    <div style={{ width: "80px", height: '80px' }}>

                    </div>
                  </Col>
                  <Col span={17}>
                    <div style={{ marginTop: '5px', fontSize: "12px", color: '#C9C9C9' }}>
                      <Form.Item
                        name="target"
                        style={{ width: '60%', marginTop: '25px', }}
                        layout="horizontal"
                        {...formItemLayout}
                        rules={
                          [{ required: true, message: '请输入交付目标' }]}>
                        {(
                          <span style={{ display: 'flex', alignItems: 'center' }}>
                            <div style={{ width: '60px', fontSize: "14px", color: '#C9C9C9' }}>目标</div>
                            <InputNumber
                              min={1}
                              max={99}
                              size="middle"
                              precision={0}
                              initialValues={1}
                              addonBefore={<span onClick={this.onReduce}>-</span>}
                              addonAfter={<span onClick={this.onAdd}>+</span>}
                              className={styles.InputNumber}
                            // onChange={this.onChange}

                            />
                          </span>

                        )}
                      </Form.Item>
                    </div>
                  </Col>
                </Row>
                <Row
                  type="flex"
                  justify="space-between"
                  align="middle"
                  gutter={0}
                  style={{ padding: '0px 10px', color: '#fff' }}>
                  <Col >
                    <div style={{ fontSize: "14px", color: "#333333" }}>
                      说明：
                    </div>
                  </Col>
                  <Col span={21}>
                    <div style={{ marginTop: 5, fontSize: "12px", color: '#58A3F7' }} >
                      {tips}
                    </div>
                  </Col>

                </Row>
                <div style={{ width: '100%' }}>
                  <Form.Item name="description" style={{ width: '100%', marginTop: '10px', color: '#fff' }} rules={
                    [{
                      required: true,
                      message: '请输入交付目标说明',
                    }, { max: 200, message: '交付目标说明内容超出限定范围（200字）' }]}>
                    {(
                      <Input.TextArea style={{ width: '100%', height: '200px' }} placeholder="请输入交付目标说明" />
                    )}
                  </Form.Item>
                </div>

              </Form>
            </div>
          </Popup>


          {/* 详情 */}
          <Popup
            visible={detailVisible}
            onMaskClick={this.onClose}
            bodyStyle={{
              borderTopLeftRadius: '10px',
              borderTopRightRadius: '10px',
              minHeight: '50vh',
            }}
          >
            <div style={{ fontSize: '16px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '10px', borderBottom: '1px solid #ccc' }}>
              <span></span>
              <span>{'数据详情'}</span>
              <Button
                type="link"
                onClick={this.onClose}
                style={{
                  fontSize: '16px',
                }}
              >
                关闭
              </Button>
            </div>
            <div style={{ padding: '10px' }}>
              <Form {...formItemLayout} >
                <Row
                  type="flex"
                  justify="space-between"
                  align="middle"
                  gutter={0}
                  style={{ padding: '14px 10px 0px 10px', color: '#fff' }}
                >
                  <Col >
                    <div style={{ width: "80px", height: '80px' }}>
                      {detailData.sysUserHead ? (
                        <Avatar src={detailData.sysUserHead} size={80} />
                      ) : (
                        <Avatar icon={<UserOutlined />} size={80} />
                      )}
                    </div>
                  </Col>
                  <Col span={17} >
                    <div
                      style={{ fontSize: "15px", color: "#333333" }}
                      title={detailData?.staffName || detailData?.staffName}
                    >
                      {detailData?.staffName || detailData?.staffName}
                    </div>
                    <div
                      style={{ marginTop: 5, fontSize: "13px", color: '#C9C9C9' }}
                      title={detailData?.deptName + '-' + detailData?.staffJobName}
                    >
                      部门：{detailData?.deptName}
                    </div>
                    <div
                      style={{ marginTop: 5, fontSize: "13px", color: '#C9C9C9' }}
                      title={detailData?.deptName + '-' + detailData?.staffJobName}
                    >
                      职务：{detailData?.staffJobName}
                    </div>
                  </Col>
                </Row>
                <Row
                  type="flex"
                  justify="space-between"
                  align="middle"
                  gutter={0}
                  style={{ padding: '0px 10px', color: '#fff' }}>
                  <Col >
                    <div style={{ width: "60px", height: '60px' }}>
                    </div>
                  </Col>
                  <Col >
                    <div style={{ marginTop: 5, fontSize: "13px", color: '#C9C9C9' }}>
                      目标：{<span style={{ color: '#333333', fontSize: "19px" }}>{detailData?.target}</span>}
                    </div>
                  </Col>
                  <Col span={11}>
                    <div
                      style={{ marginTop: 5, fontSize: "13px", color: '#C9C9C9' }}
                    >
                      已完成：{<span style={{ color: '#1891FF', fontSize: "19px" }}>{detailData?.completion}</span>}
                    </div>
                  </Col>
                </Row>
                <Row
                  type="flex"
                  justify="space-between"
                  align="middle"
                  gutter={0}
                  style={{ padding: '0px 10px', color: '#fff' }}>
                  <Col >
                    <div style={{ fontSize: "15px", color: "#333333" }}>
                      说明
                    </div>
                  </Col>
                </Row>
                <Row
                  type="flex"
                  justify="space-between"
                  align="middle"
                  gutter={0}
                  style={{ marginTop: '10px', padding: '0px 10px', color: '#fff' }}>
                  <Col >
                    <div style={{ fontSize: "13px", color: '#C9C9C9' }}>
                      {detailData?.description}
                    </div>
                  </Col>
                </Row>
              </Form>
            </div>
          </Popup>

          {/* 警告 */}
          <Popup
            visible={warnVisible}
            onMaskClick={this.onClose}
            bodyStyle={{
              borderTopLeftRadius: '10px',
              borderTopRightRadius: '10px',
              minHeight: '30vh',
            }}
          >
            <div style={{ fontSize: '16px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '10px', borderBottom: '1px solid #ccc' }}>
              <span></span>
              <span>{'警告'}</span>
              <Button
                type="link"
                onClick={this.onClose}
                style={{
                  fontSize: '16px',
                }}
              >
                关闭
              </Button>
            </div>
            <div style={{ padding: '50px', alignItems: 'center', display: 'flex', fontSize: '16px' }}>
              {message}
            </div>
          </Popup>
        </div>
      </ConfigProvider>
    );
  }
};
